/**
  ******************************************************************************
  * @file    main.c
  * @author  AE Team
  * @version 1.0.3
  * @date    2024-05-28
  * @brief   本样例演示UART1作为LIN的从机和主机进行通信
  *          主机发送随机的8字节数据给从机，紧接着读回上一帧发送的8字节数据
  *          通过UART2向PC打印LOG信息
  *
  * @note    硬件平台：SYM32L010_StartKit_V1.0
  *          接线说明：短接J13
  *                    断开J12、J23、J19
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2024 SIYIMicro.
  * All rights reserved.</center></h2>
  *
  *
  ******************************************************************************
  */


/******************************************************************************/
/* Include files                                                              */
/******************************************************************************/
#include "main.h"
#include "sym32l010_hal_sysctrl.h"
#include "sym32l010_hal_systick.h"
#include "sym32l010_hal_flash.h"
#include "sym32l010_hal_gpio.h"
#include "sym32l010_hal_uart.h"
#include "sym32l010_startkit_board.h"

#include "lin.h"
#include "stdlib.h"

/******************************************************************************/
/* Local pre-processor symbols/macros ('#define')                             */
/******************************************************************************/
#define UART_LIN    SYM_UART1
#define UART_PRINT  SYM_UART2

/******************************************************************************/
/* Global variable definitions (declared in header file with 'extern')        */
/******************************************************************************/
UART_HandleTypeDef hUart;

/******************************************************************************/
/* Local type definitions ('typedef')                                         */
/******************************************************************************/

/******************************************************************************/
/* Local function prototypes ('static')                                       */
/******************************************************************************/
static void LIN_Port_Init(void);

/******************************************************************************/
/* Local variable definitions ('static')                                      */
/******************************************************************************/

/******************************************************************************/
/* Local pre-processor symbols/macros ('#define')                             */
/******************************************************************************/

/******************************************************************************/
/* Function implementation - global ('extern') and local ('static')           */
/******************************************************************************/


/*******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 **
 ******************************************************************************/
int32_t main(void)
{
    uint8_t PId, CalcCheckSum = 0, CheckSum = 0;

    HAL_StatusTypeDef   LinRecvState;

    MemClr(&hUart, sizeof(hUart));
    MemClr(&LinRecvState, sizeof(LinRecvState));

    // 使能外设时钟
    HAL_SYSCTRL_UART1_CLK_ENABLE();                                   // UART1作为LIN传输
    HAL_SYSCTRL_UART2_CLK_ENABLE();                                   // UART2作为UART向PC打印Log

    // 配置HSI时钟
    HAL_SysCtrl_HSI_SetDiv(HSIOSC_TO_HSI8MHZ);

    // 初始化SysTick
    HAL_InitTick(8000000);

    // Print(UART2) Port And LIN(UART1) Port Init.
    Bsp_Uart_Init(8000000, 115200);
    printf("Print(Uart2) Init.\r\n");

    LIN_Port_Init();

    // Init UART_LIN As LIN Mode
    hUart.Instance = UART_LIN;
    hUart.Init.PclkFreq = 8000000;
    hUart.Init.BaudRate = 20000;
    HAL_UART_Init(&hUart);
    HAL_UART_TXD_Enable(UART_LIN);
    HAL_UART_RXD_Enable(UART_LIN);
    HAL_LIN_Enable(UART_LIN, LIN_BRKLEN_11BIT);
    printf("LIN(Uart1) Slave Init\r\n");

    while (1)
    {
        /*******************接收主机帧头*******************/
        LIN_RecvBreak_Polling(&hUart, 0);                             // 接收间隔段，一直等待

        LinRecvState = LIN_RecvSync_Polling(&hUart, 10);              // 接收同步段字符，等待10mS
        if (LinRecvState == HAL_TIMEOUT)
        {
            printf("FAIL, RecvSync TimeOut\r\n");
            continue;
        }

        LinRecvState = LIN_RecvData_Polling(&hUart, &PId, 1, 10);     // 接收1字节的PID，等待超时10ms
        if ((LinRecvState == HAL_TIMEOUT) || (PId == 0x00) || (PId == 0xFF))
        {
            printf("FAIL, RecvPID Error, PID = %2x\r\n", PId);
            continue;
        }

        /*******************从机应答*******************/
        switch (PId)
        {
            case LIN_USER_PID_RXDATA:                                 // 对应ID = 0x05, 从机应该接收8字节数据
            {
                if (LIN_RecvData_Polling(&hUart, UserRecvBuf, DATA_LEN, DATA_LEN*10) == HAL_TIMEOUT) //接收8字节数据
                {
                    printf("FAIL, Recv8Data TimeOut\r\n");
                    break;
                }

                if (LIN_RecvData_Polling(&hUart, &CheckSum, 1, 10) == HAL_TIMEOUT) // 接收校验和
                {
                    printf("FAIL, RecvCheckSum TimeOut\r\n");
                    break;
                }

                CalcCheckSum = LIN_CalcCheckSum(UserRecvBuf, DATA_LEN); // 计算校验和
                if ((CalcCheckSum + CheckSum) != 0xFF)
                {
                    printf("FAIL, CalcCheckSum Error\r\n");
                    break;
                }

                printf("PASS, ID = 0x05\r\n");
                break;
            }
            case LIN_USER_PID_TXDATA:                                 // 对应ID = 0x16, 从机应该返回8字节数据
            {
                LIN_Delay_nBit(&hUart, 30);                           // 等待接收方准备完毕
                LIN_SendData_Polling(&hUart, UserRecvBuf, DATA_LEN, 0); // 发送8字节数据
                CalcCheckSum = LIN_CalcCheckSum(UserRecvBuf, DATA_LEN); // 计算校验和
                CalcCheckSum = ~CalcCheckSum;
                LIN_SendData_Polling(&hUart, &CalcCheckSum, 1, 0);    // 发送校验和

                printf("PASS, ID = 0x16\r\n");
                break;
            }
            default:                                                  // 无效ID
            {
                printf("FAIL, ID = Err\r\n");
                break;
            }
        }
    }
}


/*******************************************************************************
 * @brief  LIN 端口初始化
 * @param  None
 * @retval None
 * @note
 */
static void LIN_Port_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    MemClr(&GPIO_InitStruct, sizeof(GPIO_InitStruct));

    HAL_SYSCTRL_GPIOA_CLK_ENABLE();

    // Config PA06 AS UART1.TXD <--> LIN
    AFx_UART1TXD_PA06();
    GPIO_InitStruct.Pins = GPIO_PIN_6;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    HAL_GPIO_Init(SYM_GPIOA, &GPIO_InitStruct);

    // Config PA05 AS UART1.RXD <--> LIN
    AFx_UART1RXD_PA05();
    GPIO_InitStruct.Pins = GPIO_PIN_5;
    GPIO_InitStruct.Pull = GPIO_PULL_UP;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    HAL_GPIO_Init(SYM_GPIOA, &GPIO_InitStruct);
}

/*******************************************************************************
 ** EOF (not truncated)
 ******************************************************************************/
#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
    /* USER CODE BEGIN */
    /* User can add his own implementation to report the file name and line number,
       tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
    /* USER CODE END */
}
#endif /* USE_FULL_ASSERT */


/************************ (C) COPYRIGHT SIYIMicro *****END OF FILE*************/
